package com.app.util;

import java.io.File;
import java.io.IOException;
import java.util.LinkedHashMap;

import com.app.util.file.obj.ObjectReader;
import com.app.util.file.obj.ObjectWriter;

public class StoragedLinkedHashMap<T, E> extends LinkedHashMap<T, E> {

	private static final long serialVersionUID = -6078183892853632804L;

	private transient boolean changed; 
	private transient File file;

	@SuppressWarnings("unchecked")
	public static StoragedLinkedHashMap fromFile(File file) throws IOException, ClassNotFoundException {
		StoragedLinkedHashMap storagedMap;
		if (file.exists() && file.length() > 0) {
			ObjectReader or = new ObjectReader(file);
			try {
				storagedMap = (StoragedLinkedHashMap) or.next();
			} finally {
				or.close();
			}
		} else {
			storagedMap = new StoragedLinkedHashMap();
		}
		if (null != storagedMap) {
			storagedMap.file = file;
		}
		return storagedMap;
	}

	private StoragedLinkedHashMap() {
	}

	public E put(T key, E value) {
		E o = super.put(key, value);
		changed = true;
		return o;
	}

	public void save() throws IOException {
		ObjectWriter ow = new ObjectWriter(file);
		try {
			ow.writeObject(this);
			changed = false;
		} finally {
			ow.close();
		}
	}

	public boolean isChanged() {
		return changed;
	}
}
